package learnsicp;

import java.util.Arrays;

public class RMDemo {

	public static void main(String[] args) {
		int[] arr1 = { 1, 2, 3 };
		int[] arr2 = {};
		int[] arr3 = { 1, 2, 3, 4, 2 };

		System.out.println(Arrays.toString(rm(2, arr1))); // [1, 3]
		System.out.println(Arrays.toString(rm(5, arr1))); // [1, 2, 3]
		System.out.println(Arrays.toString(rm(2, arr2))); // []
		System.out.println(Arrays.toString(rm(2, arr3))); // [1, 3, 4, 2]

	}

	public static int[] rm(int x, int[] arr) {
		return rm1(x, arr);
	}

	private static int[] rm1(int x, int[] arr) {
		int i = 0;
		found: {
			for (; i < arr.length; i++) {
				if (x == arr[i]) {
					break found;
				}
			}
			return arr;
		}

		return remove(arr, i);
	}

	private static int[] rm0(int x, int[] arr) {
		int targetIndex = -1;
		for (int i = 0; i < arr.length; i++) {
			if (x == arr[i]) {
				targetIndex = i;
				break;
			}
		}
		if (targetIndex == -1) {
			return arr;
		}

		return remove(arr, targetIndex);
	}

	private static int[] remove(int[] arr, int index) {
		int[] newArr = new int[arr.length - 1];
		int newIndex = 0;
		for (int i = 0; i < arr.length; i++) {
			if (i == index) {
				continue;
			}
			newArr[newIndex++] = arr[i];
		}
		return newArr;
	}

}
